// 存储扩展窗口的ID
let extensionWindowId = null;

// 检查并激活已存在的窗口，如果不存在则创建新窗口
async function openOrFocusPopup() {
    // 如果存在窗口ID，先检查窗口是否还在
    if (extensionWindowId !== null) {
        try {
            const window = await chrome.windows.get(extensionWindowId);
            // 如果窗口存在，则激活它
            if (window) {
                await chrome.windows.update(extensionWindowId, {
                    focused: true,
                    drawAttention: true
                });
                return;
            }
        } catch (e) {
            // 如果窗口不存在，extensionWindowId 设为 null
            extensionWindowId = null;
        }
    }

    // 如果没有现有窗口，创建新窗口
    chrome.windows.getCurrent(function(window) {
        const popupWidth = 500;
        const popupHeight = 600;
        
        // 计算居中位置
        const left = Math.round((window.width - popupWidth) / 2 + window.left);
        const top = Math.round((window.height - popupHeight) / 2 + window.top);

        // 创建新窗口
        chrome.windows.create({
            url: 'popup.html',
            type: 'popup',
            width: popupWidth,
            height: popupHeight,
            left: left,
            top: top
        }, function(newWindow) {
            // 保存新窗口的ID
            extensionWindowId = newWindow.id;
        });
    });
}

// 监听窗口关闭事件
chrome.windows.onRemoved.addListener(function(windowId) {
    // 如果关闭的是扩展窗口，清除存储的窗口ID
    if (windowId === extensionWindowId) {
        extensionWindowId = null;
    }
});

// 点击扩展图标时的处理
chrome.action.onClicked.addListener(function() {
    openOrFocusPopup();
});

// 监听快捷键
chrome.commands.onCommand.addListener(function(command) {
    if (command === "_execute_action") {
        openOrFocusPopup();
    }
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'moveWindowToBack') {
    chrome.windows.getCurrent(window => {
      chrome.windows.update(window.id, { focused: false });
    });
  }
}); 